package com.mxpio.erp.purchase.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.common.purchase.entity.*;
import com.mxpio.erp.common.quality.entity.InQualityOrder;
import com.mxpio.erp.common.quality.entity.InQualityOrderLine;
import com.mxpio.erp.common.vo.NoticeClassVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.WarehouseOrderLine;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.policy.OrderContext;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.purchase.service.PurchaseOrderLineService;
import com.mxpio.erp.common.purchase.service.PurchaseOrderService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.purchase.policy.impl.DefaultPurchasePolicy;
import com.mxpio.erp.purchase.policy.impl.DefaultRejectPolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "PurchaseOrderController", description = "采购订单数据接口")
@RestController
@RequestMapping("/erp/purc/po/")
public class PurchaseOrderController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderLineService purchaseOrderLineService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderLineService orderLineService;
    @GetMapping("list")
    @Operation(summary = "采购订单列表", description = "获取采购订单（无分页）", method = "GET")
    public Result<List<PurchaseOrder>> list(Criteria criteria) throws UnsupportedEncodingException {
        List<PurchaseOrder> purchaseOrders = purchaseOrderService.listCollect(PurchaseOrder.class, criteria, "pnCode", Supply.class, "pnCode");
        return Result.OK(purchaseOrders);
    }

    @GetMapping("page")
    @Operation(summary = "采购订单列表", description = "获取采购订单（分页）", method = "GET")
    public Result<Page<PurchaseOrder>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<PurchaseOrder> purchaseOrders = purchaseOrderService.listPageCollect(PurchaseOrder.class, page, criteria, "pnCode", Supply.class, "pnCode");
        return Result.OK(purchaseOrders);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据bizNo获取采购订单", description = "根据bizNo获取采购订单", method = "GET")
    public Result<PurchaseOrder> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder purchaseOrder = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        return Result.OK(purchaseOrder);
    }

    @PostMapping("add")
    @Operation(summary = "新增采购订单", description = "新增采购订单", method = "POST")
    public Result<PurchaseOrder> add(@RequestBody PurchaseOrder purchaseOrder) {
        purchaseOrderService.save(purchaseOrder);
        return Result.OK(purchaseOrder);
    }

    @RequestMapping("save")
    @Operation(summary = "保存采购订单", description = "保存采购订单")
    public Result<PurchaseOrder> save(@RequestBody PurchaseOrder purchaseOrder) {
        purchaseOrderService.save(purchaseOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof PurchaseOrderLine){
        			PurchaseOrder purchaseOrder = context.getParent();
                    ((PurchaseOrderLine) o).setBizNo(purchaseOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(purchaseOrder);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑采购订单", description = "编辑采购订单", method = "PUT")
    public Result<PurchaseOrder> edit(@RequestBody PurchaseOrder purchaseOrder) {
        purchaseOrderService.update(purchaseOrder);
        return Result.OK(purchaseOrder);
    }

    @DeleteMapping("remove/{bizNo}")
    @Operation(summary = "根据bizNo删除采购订单", description = "根据bizNo删除采购订单,多个bizNo用英文逗号分隔", method = "DELETE")
    public Result<PurchaseOrder> remove(@PathVariable(name = "bizNo", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for (String key : bizNo) {
            Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
            purchaseOrderLineService.removeBatch(PurchaseOrderLine.class, c);
            purchaseOrderService.remove(PurchaseOrder.class, key);
        }
        return Result.OK();
    }

    @PutMapping("open/{bizNo}")
    @Operation(summary = "打开采购订单", description = "打开采购订单", method = "PUT")
    public Result<? extends Order> open(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        return orderService.updateCloseStatus(po, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @Operation(summary = "关闭采购订单", description = "关闭采购订单", method = "PUT")
    public Result<? extends Order> close(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        return orderService.updateCloseStatus(po, OrderStatusEnums.CloseStatus.CLOSED);
    }

    @PutMapping("submit/{bizNo}")
    @Operation(summary = "提交采购订单", description = "提交采购订单", method = "PUT")
    public Result<? extends Order> submit(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        if (po.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())) {
            return orderService.updateBpmnStatus(po, OrderStatusEnums.BpmnStatus.AUDITING);
        } else {
            return Result.error("非开立状态不可提交");
        }
    }

    @PutMapping("audit/{bizNo}")
    @Operation(summary = "审核采购订单", description = "审核采购订单", method = "PUT")
    public Result<? extends Order> audit(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        if (po.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
            return orderService.updateBpmnStatus(po, OrderStatusEnums.BpmnStatus.AUDITED);
        } else {
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("abandon/{bizNo}")
    @Operation(summary = "弃审采购订单", description = "弃审采购订单", method = "PUT")
    public Result<? extends Order> abandon(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        if (!po.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode()) && !po.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            return Result.error("非审核中、已审核状态不可弃审");
        }
        if (!po.getOrderStatus().equals(OrderStatusEnums.OrderStatus.PLAN.getStatusCode())&&!po.getOrderStatus().equals(OrderStatusEnums.OrderStatus.ORDERED.getStatusCode())){
            return Result.error("执行状态非计划、下达时不可弃审");
        }
        return orderService.updateBpmnStatus(po, OrderStatusEnums.BpmnStatus.CREATE);
    }

    @GetMapping("wo/{bizNo}")
    @Operation(summary = "反查入库单列表", description = "反查入库单列表", method = "GET")
    public Result<List<WarehouseOrderLine>> listwo(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
       //TODO: 入库单尚未开发
        List<WarehouseOrderLine> WarehouseOrderLines = new ArrayList<>();
        return Result.OK(WarehouseOrderLines);
    }


    @RequestMapping("execute/receive/{bizNo}")
    @Operation(summary = "", description = "收货")
    public Result<Object> receiveExec(@PathVariable(name = "bizNo", required = true) String bizNo,
                                   @RequestBody OrderExcuteVo orderExcuteVo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        OrderContext context = orderService.execute(po, new DefaultPurchasePolicy(orderExcuteVo.getLines(),orderLineService));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }

    @RequestMapping("execute/reject/{bizNo}")
    @Operation(summary = "退货", description = "退货")
    public Result<Object> rejectExec(@PathVariable(name = "bizNo", required = true) String bizNo,
                                     @RequestBody OrderExcuteVo orderExcuteVo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        OrderContext context = orderService.execute(po, new DefaultRejectPolicy(orderExcuteVo.getLines(),orderLineService));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }


    @PutMapping("finish/{bizNo}")
    @Operation(summary = "采购订单强制完成", description = "采购订单强制完成", method = "PUT")
    public Result<? extends Order> finish(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        if(OrderStatusEnums.OrderStatus.PROCESSING.getStatusCode().equals(po.getOrderStatus())){
            //校验明细 是否存在未执行完毕的收、退货记录
            Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, bizNo);
            List<PurchaseOrderLine> orderLines = purchaseOrderLineService.list(PurchaseOrderLine.class, c);
            if (orderLines.size()>0){
                //计算数量字段
                NoticeClassVo receivingNoticeClazz = new NoticeClassVo(ReceivingNotice.class, ReceivingNoticeLine.class);
                NoticeClassVo rejectNoticeClazz = new NoticeClassVo(RejectNotice.class, RejectNoticeLine.class);
                NoticeClassVo inQualityOrderClazz = new NoticeClassVo(InQualityOrder.class, InQualityOrderLine.class);//增加入库验收单 数据统计
                List<NoticeClassVo> noticeClassVos = new ArrayList<>();
                noticeClassVos.add(receivingNoticeClazz);
                noticeClassVos.add(rejectNoticeClazz);
                noticeClassVos.add(inQualityOrderClazz);
                orderLineService.handleBizOrderLineQuantity(orderLines, noticeClassVos, OrderEnums.AccessType.IN.getCode());
                for (PurchaseOrderLine orderItem:orderLines){
                    if ((orderItem.getPlanQuantity()!=null &&orderItem.getPlanQuantity().compareTo(BigDecimal.ZERO)!=0)
                            || (orderItem.getPlanRejectQuantity()!=null && orderItem.getPlanRejectQuantity().compareTo(BigDecimal.ZERO)!=0)){
                        return Result.error("订单行存在未执行完毕的收货、退货记录，无法执行完成订单操作。");
                    }
                }
            }
            return orderService.updateOrderStatus(po, OrderStatusEnums.OrderStatus.FINISHED);
        }else{
            return Result.error("非执行状态不可执行完成订单操作");
        }
    }

    @PutMapping("clear/{bizNo}")
    @Operation(summary = "结算采购订单", description = "结算采购订单", method = "PUT")
    public Result<? extends Order> clear(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        PurchaseOrder po = purchaseOrderService.getById(PurchaseOrder.class, bizNo);
        if(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode().equals(po.getOrderStatus())){
            return orderService.updateOrderStatus(po, OrderStatusEnums.OrderStatus.CLEARED);
        }else{
            return Result.error("非已完成状态不可执行”结算结清“操作");
        }
    }

    @GetMapping("printlist/{bizNos}")
    @Operation(summary = "根据bizNos获取采购订单打印数据", description = "根据bizNos获取采购订单打印数据（主单包含供应商对象信息，明细包含请购单明细行对象数据）", method = "GET")
    public Result<List<PurchaseOrder>> getByIds(@PathVariable(name = "bizNos", required = true) String bizNos) {
        return purchaseOrderService.getPrintsListByIds(bizNos);
    }
}


